<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue'
  import { message } from 'ant-design-vue'
  import type { UploadProps } from 'ant-design-vue'
  import { createArticleReq, editArticleReq, uploadSingleFileReq } from '@/api'

  const props = defineProps(['subCategoryId', 'record'])

  interface FormState {
    title: string
    keyLevel: string
    content: string
  }

  const formState = reactive<FormState>({
    title: props.record?.title || '',
    keyLevel: props.record?.keyLevel || '',
    content: props.record?.content || '',
  })

  const formRef = ref()

  const showModal = defineModel()

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(async () => {
        if (props.record) {
          const res = await editArticleReq({
            id: props.record.id,
            subCategoryId: props.record.subCategoryId,
            ...formState,
          })
          if (res?.data) {
            message.success('文章编辑成功')
            showModal.value = false
          } else {
            message.error('文章编辑失败')
          }
        } else {
          const subCategoryId = props.subCategoryId
          const res = await createArticleReq({
            ...formState,
            subCategoryId,
          })
          if (res?.data) {
            message.success('文章创建成功')
            showModal.value = false
          } else {
            message.error('文章创建失败')
          }
        }
      })
      .catch(() => {})
  }

  const fileList = ref<UploadProps['fileList']>([])

  const beforeUpload = (file: any) => {
    // 提取扩展名并转小写
    if (fileList.value && fileList.value.length > 0) {
      message.error('只能上传一个文件！')
      return false
    }
    const ext = file.name.split('.').pop().toLowerCase()
    const isMdFile = ext === 'md' || ext === 'markdown'
    const isLt100k = file.size / 1024 < 100 // 限制100kb
    if (!isMdFile) {
      message.error('仅支持md文件！')
      return false
    }
    if (!isLt100k) {
      message.error('文件不能超过100kb！')
      return false
    }
    fileList.value = [...(fileList.value || []), file]
    return false // 通过校验
  }

  const uploading = ref<boolean>(false)

  const handleRemove: UploadProps['onRemove'] = (file) => {
    if (!fileList.value) return
    const index = fileList.value.findIndex((f) => f.uid === file.uid)
    if (index > -1) {
      const newFileList = fileList.value.slice()
      newFileList.splice(index, 1)
      fileList.value = newFileList
    }
  }

  // 手动上传文件
  const handleManualUpload = async () => {
    if (!fileList.value || fileList.value.length === 0) return
    const formData = new FormData()
    formData.append('file', fileList.value[0] as any)

    uploading.value = true
    try {
      const res: any = await uploadSingleFileReq(formData)
      if (res?.code === 201 && res.data?.path) {
        message.success(`${fileList.value[0].name} 上传成功`)
        formState.content = res.data?.path
      } else {
        message.error(`${fileList.value[0].name} ${res?.message}`)
      }
    } catch (error) {}
    uploading.value = false
  }

  // 如果有文件，则获取文件
  const getFile = async (content: string) => {
    const res = await fetch(`${import.meta.env.VITE_APP_BASE_API}${content}`)
    const blob = await res.blob()
    const filename = content.split('/').pop() || 'file.md'
    const file = new File([blob], filename, { type: blob.type })
    return file
  }

  onMounted(async () => {
    if (props.record?.content) {
      const file = await getFile(props.record.content)
      if (file) {
        fileList.value = [
          {
            uid: '-1',
            name: file.name,
            status: 'done',
          },
        ]
      }
    }
  })
</script>

<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="createArticleForm"
    style="padding: 20px"
  >
    <a-form-item
      name="title"
      label="名称"
      :validate-trigger="['']"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
      :rules="[{ required: true, message: '名称不能为空' }]"
    >
      <a-input v-model:value.trim="formState.title" />
    </a-form-item>

    <a-form-item
      name="keyLevel"
      label="重点级别"
      :validate-trigger="['']"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <a-input v-model:value.trim="formState.keyLevel" />
    </a-form-item>

    <a-form-item
      name="content"
      label="内容文档"
      :validate-trigger="['']"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <!-- name="file" 后端接收的字段名-->
      <a-upload
        :file-list="fileList"
        name="file"
        :before-upload="beforeUpload"
        @remove="handleRemove"
      >
        <a-button>
          <UploadOutlined />
          选择文档
        </a-button>
        <span style="margin-left: 16px; color: rgba(0, 0, 0, 0.5)">
          md文件,小于100kb
        </span>
      </a-upload>
      <a-button
        @click="handleManualUpload"
        :disabled="!fileList || fileList.length === 0"
        :loading="uploading"
        style="margin-top: 10px"
      >
        开始上传
      </a-button>
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button
        type="primary"
        style="width: 200px; height: 40px"
        @click="onSubmit"
        >提交</a-button
      >
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less"></style>
